<script setup>
import { ref, reactive, onMounted, watch, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fileApi, api } from '@/service/api.ts';
import { showConfirmDialog, showToast, showNotify } from "vant";

const { config } = defineProps({
  config: {
    type: Object,
    required: true,
  }
});
const emits = defineEmits(['change']);

const Rt = reactive({
  filelist: (config.value || []).map(i => {
    return { oldURL: i.url, url: api + i.url, name: i.name }
  }),
  canShowRemoveDialog: true,/* 删除弹窗标志，上传不符合格式的文件会触发beforeRemove，此时不弹窗 */
});
const handleBeforeUpload = (file) => {
  const isLtMaxSize = file.size / 1024 / 1024 < config.maxMB; // 检查文件大小是否小于maxMB
  if (!isLtMaxSize) {
    ElMessage.error(`文件大小不能超过 ${config.maxMB}MB！`);
    Rt.canShowRemoveDialog = false; // 禁止显示删除弹窗
    return false;
  }
  return true; // 返回 true 表示允许上传，返回 false 表示禁止上传
}
const handleFileUpload = (option) => {
  let formData = new FormData();
  formData.append('file', option.file);
  formData.append('ftype', '表单附件');
  formData.append('name', option.file.name);
  fileApi({
    method: 'post',
    data: formData,
  }).then(res => {
    option.onSuccess(res, option.file);
  }).catch(error => {
    option.onError(error);
  });
}
const handleSuccess = (response, file, fileList) => {
  const data = fileList.map(i => {
    return { url: i.response?.file_url || i.oldURL, name: i.response?.name || i.name };
  });
  emits('change', data);
}

const beforeRemove = (uploadFile, uploadFiles) => {
  if (Rt.canShowRemoveDialog) {
   return showConfirmDialog({
      title: '提示',
      message: `移除附件 ${uploadFile.name} ?`,
    }).then(() => {
      return true;
    }).catch(() => {
      return false
      // on cancel
    });
  } else {
    Rt.canShowRemoveDialog = true;/* 重置状态 */
    return true;
  }
}
const handleRemove = (file, uploadFiles) => {
  const data = uploadFiles.map(i => {
    return { url: i.response?.file_url || i.oldURL, name: i.response?.name || i.name };
  });
  emits('change', data);
}
</script>

<template>
  <div class="box">
    <el-upload class="upload-demo" v-model:file-list="Rt.filelist" :limit="config.limit"
      :disabled="Rt.filelist.length >= config.limit" multiple :before-upload="handleBeforeUpload"
      :http-request="handleFileUpload" :on-success="handleSuccess" :before-remove="beforeRemove"
      :on-remove="handleRemove">
      <el-button type="primary" :disabled="Rt.filelist.length >= config.limit">
        上传附件
      </el-button>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
.box {
  display: block;
  width: 100%;
}
</style>